import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes ,updateDynamicRoutes} from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import { useInfoStore } from '@/store/modules/info.js'
import { GetRoleMenuList,GetResourceList } from '@/api/api_2.js'
import { handleTree } from '@/utils/ruoyi'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: []
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      generateRoutes(roles) {
        return new Promise(resolve => {
          // 个人信息
          const info = useInfoStore().info;
          // 超级管理员--使用静态路由
          if (info?.role?.level===0) {
            this.setRoutes(dynamicRoutes)
            this.setSidebarRouters(constantRoutes.concat(dynamicRoutes))
            this.setDefaultRoutes(dynamicRoutes)
            this.setTopbarRoutes(dynamicRoutes)
            resolve(dynamicRoutes)
          }else{
            // 查询当前用户拥有的权限路由
            let Routes = [];
            GetRoleMenuList({
              roleID: info.roleID,
              resourcesID: -1,
            }).then((response) => {
              let list = response.data;
              if (list?.length > 0) {
                // 提取出所有的 resourcesID 组成 Routes 数组
                Routes = list.map((item) => item.resourcesID);
                // 查询当前系统全部路由信息
                GetResourceList({
                  reName: "",
                  rePath: "",
                  tenantID: info.systemID,
                  reParetntID: -1,
                }).then((response2) => {
                  response2.data.forEach((element) => {
                    element.children = [];
                  });
                  // 筛选出 response2.data 中 resourcesID 在 Routes 中的路由
                  const matchedRoutes = response2.data.filter((item) => {
                    return Routes.includes(item.id);
                  });
                  // 处理成树形结构
                  let apiData = handleTree(matchedRoutes);
                  const routes = convertToRoutes(apiData);
                  if (routes?.length > 0) {
                    routes.unshift({
                      path: "/",
                      component:Layout,
                      redirect: routes[0].path,
                    });
                  }
                  // console.log('处理后的动态路由');
                  // console.log(routes);
                  updateDynamicRoutes(routes);
                  this.setRoutes(routes);
                  this.setSidebarRouters(constantRoutes.concat(routes));
                  this.setDefaultRoutes(routes);
                  this.setTopbarRoutes(routes);
                  resolve(routes);
                });
              } else {
                resolve(null);
              }
            });
          }
        })
      }
    }
  })
  
// 递归处理树状结构的路由数据
function convertToRoutes(data) {
  return data.map(node => {
      const route = {
          path: node.rePath,
          name: node.rePath,
          meta: {
              title: node.reName,
              icon: node.reIcon,
              noCache: false
          },
          children: []
      };
      if (node.reParetntID === 0) {
          // route.component = () => Layout;
          route.component = Layout
          route.name =  '';
      } else {
          // 确保路径是相对固定的格式
          route.component = loadView(node.reValue);
      }
      if (node.children && node.children.length > 0) {
          route.children = convertToRoutes(node.children);
      }else {
      // delete route['children']
      delete route['redirect']
    }
      return route;
  });
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach(el => {
    el.path = lastRouter ? lastRouter.path + '/' + el.path : el.path
    if (el.children && el.children.length && el.component === 'ParentView') {
      children = children.concat(filterChildren(el.children, el))
    } else {
      children.push(el)
    }
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

// 修改 loadView 函数以支持路由懒加载
export const loadView = (view) => {
  const modules = import.meta.glob('./../../views/**/*.vue');
  for (const path in modules) {
    const dir = path.split('views')[1].split('.vue')[0];
    if (dir === view) {
      return modules[path];
    }
  }
  return null;
  // 使用 import 实现生产环境的路由懒加载
  // return () => import(`@/views${view}.vue`)
};

export default usePermissionStore
